#include "cSound.h"
#include "cLog.h"
#include "SDL.h"
#include "SDL_mixer.h"
#include <string>
#include <iostream>
#include <fstream>

cSound::cSound(void)
{
	Log = cLog::Instance();
	gameMusics.reserve(MAX_MUSICS);
}

cSound::~cSound(void)
{    
	Mix_CloseAudio();	
}

bool cSound::Init(void)
{
  if((SDL_Init(SDL_INIT_AUDIO)==-1))
  {
     Log->Msg(SDL_GetError());
	 return false;
  }
  if(Mix_OpenAudio(FREQUENCY,FORMAT,CHANNELS,CHUNKSIZE)==-1)
  {
     Log->Msg(Mix_GetError());
	 return false;
  }
  Mix_VolumeMusic(VOLUME_LEVEL);
  return true;   
}

bool cSound::loadMusics(string filename)
{
   Mix_Music *m;
   ifstream file(filename.c_str(), ifstream::in);
      
   while(!file.eof())
   {
      file >> nameTrack;
	  m = Mix_LoadMUS(nameTrack.c_str());
      if(!m) {
	   Log->Msg(Mix_GetError());
	   return false;
	  }
      gameMusics.push_back(m);
   }
   return true;     
}

bool cSound::loadSoundEffects(string filename)
{
   Mix_Chunk *e;
   ifstream file(filename.c_str(), ifstream::in);
     
   while(!file.eof())
   {
      file >> nameTrack;
	  e = Mix_LoadWAV(nameTrack.c_str());
      if(!e) {
	   Log->Msg(Mix_GetError());
	   return false;
	  }
      soundEffects.push_back(e);
   }
   return true;     
}

void cSound::freeMusics()
{   
   for(vector<Mix_Music*>::iterator it=gameMusics.begin(); it!=gameMusics.end(); ++it)
   {
     Mix_FreeMusic(*it);
   }
   gameMusics.clear();
}

void cSound::freeSoundEffects()
{   
   for(vector<Mix_Chunk*>::iterator it=soundEffects.begin(); it!=soundEffects.end(); ++it)
   {
     Mix_FreeChunk(*it);
   }
   soundEffects.clear();
}

void cSound::play(int track,int loop)
{
   Mix_PlayMusic(gameMusics.at(track),loop);
}

void cSound::pause()
{
   Mix_PauseMusic();
}

void cSound::resume()
{
   Mix_ResumeMusic();
}

void cSound::stop()
{
   Mix_HaltMusic();
}

void cSound::playSoundEffect(int track,int loop,int channel)
{
   Mix_PlayChannel(channel,soundEffects.at(track),loop);
}